//
//  WmcRecognitionVM.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/10/18.
//

import Foundation
import YPNetwork

class WmcRecognitionVM: WmcBaseVM {
    
    private(set) var dataSource: [WmcWatermarkDetailModel] = []
    
    private(set) var selectedModel: WmcWatermarkDetailModel?
    
    func fetchRecognitionConfigList(success: @escaping ([WmcWatermarkDetailModel]) -> Void, failure: ((Error) -> Void)? = nil) {
        let type: YPWmcManager.RecognitionWatermarkGroupType = YPWmcManager.shared.recognitionWatermarkGroupType
        
        WmcWatermarkListDBManager.searchClassifyList(templateGroupKey: type.info.key) { [weak self] list in
            guard let weakSelf = self else { return }
            
            if !list.isEmpty {
                weakSelf.dataSource = list[0].watermarks
                weakSelf.setDefaultSelectedItem(list: weakSelf.dataSource)
                success(weakSelf.dataSource)
            }
            
            WmcMediaWatermarkAPI.fetchWatermarkList(watermarkIds: type.info.templateIds, success: { [weak self] list in
                guard let weakSelf = self else { return }
                if !list.isEmpty {
                    weakSelf.dataSource = list[0].watermarks
                    
                    if weakSelf.selectedModel == nil {
                        weakSelf.setDefaultSelectedItem(list: weakSelf.dataSource)
                    }
                    
                    success(weakSelf.dataSource)
                    WmcWatermarkListDBManager.insertClassifyList(templateGroupId: type.info.key, classifyList: list)
                }
            }) { error in
                failure?(error)
            }
        }
    }
    
    func setSelectedModel(_ model: WmcWatermarkDetailModel) {
        selectedModel = model
        if let json = model.toJSONString() {
            WmcUserdefault.save(value: json, forKey: .Data.Recognition.lastSelectedItem)
        }
    }
    
    private func setDefaultSelectedItem(list: [WmcWatermarkDetailModel]) {
        if let defaultItem = defaultSelectedItem(list: list) {
            selectedModel = defaultItem
            if let json = defaultItem.toJSONString() {
                WmcUserdefault.save(value: json, forKey: .Data.Recognition.lastSelectedItem)
            }
        }
    }
    
    private func defaultSelectedItem(list: [WmcWatermarkDetailModel]) -> WmcWatermarkDetailModel? {
        var result: WmcWatermarkDetailModel?
        
        if !list.isEmpty {
            result = list[0]
        }
        
        if let json: String = WmcUserdefault.object(forKey: .Data.Recognition.lastSelectedItem) {
            let lastSelectedItem = WmcWatermarkDetailModel.deserialize(from: json)
            for (_, item) in list.enumerated() {
                if lastSelectedItem?.wmId == item.wmId {
                    result = item
                    break
                }
            }
        }
        
        return result
    }
}

